<?php
/**
 * @description:
 * @author     : Geomen
 * @time       : 2018/11/6 10:08
 */
namespace App\Console;

class WebSocketServer {
    public $server;
    public $setConfig = [
        'ssl_key_file' => '/usr/local/tengine/conf/cert/214136458100676.key',
        'ssl_cert_file' => '/usr/local/tengine/conf/cert/214136458100676.pem'
    ];
    public function __construct() {
        $this->server = new swoole_websocket_server("0.0.0.0", 9502,SWOOLE_BASE,SWOOLE_SOCK_TCP|SWOOLE_SSL);
        $this->server->set($this->setConfig);
        $this->server->on('open', function (swoole_websocket_server $server, $request) {
            echo "server: handshake success with fd=>{$request->fd} open_id=>{$request->header['open_id']}\n";
            $open_id = $request->header['open_id'];
            echo exec("php /data/www/yanxi.info/www.yanxi.info/artisan socket:connect $open_id $request->fd");
        });
        $this->server->on('message', function (swoole_websocket_server $server, $frame) {
            echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n";
            $server->push($frame->fd, "this is server");
        });
        $this->server->on('close', function ($ser, $fd) {
            echo "client {$fd} closed\n";
        });
        $this->server->on('request', function ($request, $response) {
            // 接收http请求从get获取message参数的值，给用户推送
            // $this->server->connections 遍历所有websocket连接用户的fd，给所有用户推送
            foreach ($this->server->connections as $fd) {
                $this->server->push($fd, $request->get['message']);
            }
        });
        $this->server->start();
    }
}
new WebSocketServer();